package cn.iocoder.yudao.framework.msdb;

import cn.iocoder.yudao.framework.datasource.local.ThreadLocalContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * TODO
 *
 * @className: DefaultRoutingDataSource
 * @author: tangkh
 * @date: 2023-09-19 17:52
 */
public class DefaultRoutingDataSource implements ICustomizeRoutingDataSource {
    private static final Logger log = LoggerFactory.getLogger(DefaultRoutingDataSource.class);
    @Resource
    private ReadDbByPathProperties readDbByPathProperties;

    public DefaultRoutingDataSource() {
    }

    @Override
    public String getDbKey() {
        String uri = "";
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String dbkey = (String) ThreadLocalContext.getAttachment("dbKey");
        if (StringUtils.hasText(dbkey)) {
            log.info("DefaultRoutingDataSource dbkey:{},直接从ThreadLocalContext获取dbKey", dbkey);
            return dbkey;
        } else {
            if (servletRequestAttributes != null && servletRequestAttributes.getRequest() != null) {
                uri = servletRequestAttributes.getRequest().getRequestURI();
            } else {
                uri = (String)ThreadLocalContext.getAttachment("requestUri");
            }

            Map<String, String> config = this.readDbByPathProperties.getConfig();
            if (config != null) {
                Iterator var5 = config.entrySet().iterator();

                while(true) {
                    String key;
                    String value;
                    do {
                        if (!var5.hasNext()) {
                            return "";
                        }

                        Map.Entry entry = (Map.Entry)var5.next();
                        key = (String)entry.getKey();
                        value = (String)entry.getValue();
                    } while(!StringUtils.hasText(value));

                    StringTokenizer stringTokenizer = new StringTokenizer(value, ",|;");

                    while(stringTokenizer.hasMoreElements()) {
                        String item = stringTokenizer.nextToken();
                        if (StringUtils.hasText(uri) && StringUtils.hasText(item) && uri.indexOf(item) == 0) {
                            log.info("DefaultRoutingDataSource key:{},value:{},uri:{}", key, value, uri);
                            return key;
                        }
                    }
                }
            } else {
                return "";
            }
        }
    }
}
